#include "XThreadPool.h"
#include "XThread.h"
#include <thread>
#include <iostream>
#include "XTask.h"
using namespace std;

/**
 * @fn
 * @brief
 * @param[in]
 * @param[out]
 * @retval
 */
XThreadPool::XThreadPool()
{

}

/**
 * @fn
 * @brief 单例模式
 * @param[in]
 * @param[out]
 * @retval
 */
 XThreadPool* XThreadPool::GetInstance()
{
    static XThreadPool p;
    return &p;
}

/**
 * @fn
 * @brief 将任务分发给某个线程
 * @param[in]
 * @param[out]
 * @retval
 */
void XThreadPool::Dispatch(XTask *task)
{
    /* 轮询分发任务给线程 */
    if (NULL == task)
    {
        return;
    }

    lastThread = (lastThread + 1) % threadCount;
    XThread *t = threads[lastThread];

    t->AddTask(task);

    t->Activate(); //激活线程
}

/**
 * @fn
 * @brief 初始化所有线程并启动线程
 * @param[in]
 * @param[out]
 * @retval
 */
bool XThreadPool::Init(int threadCount)
{
    bool ret = true;
    this->threadCount = threadCount;
    this->lastThread = -1;

    for (int i = 0; i < threadCount; i++)
    {
        XThread *t = new XThread();
        t->setId(i);

        t->Start();//启动线程
        threads.push_back(t);
        this_thread::sleep_for(std::chrono::milliseconds(10));
    }
    return ret;
}
